package com.xiashitech.agent.instrumentation.struts2.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSStruts2ServiceActionCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.xiashitech.agent.instrumentation.struts2.XSStruts2ActionSingletons.instrumenter;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static net.bytebuddy.matcher.ElementMatchers.*;

/**
 * Deprecated
 * 本插桩在开始分派请求执行服务时插桩
 * 本插桩太靠上层，能拿到 request 和 response，但不容易拿到 action
 */
public class XSStruts2ServiceActionInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("org.apache.struts2.dispatcher.Dispatcher");
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(named("serviceAction")
            .and(takesArgument(0, named("javax.servlet.http.HttpServletRequest")))
            .and(takesArgument(1, named("javax.servlet.http.HttpServletResponse")))
            .and(takesArgument(2, named("org.apache.struts2.dispatcher.mapper.ActionMapping"))),
                XSStruts2ServiceActionInstrumentation.class.getName()+"$XSServiceAdvice");
    }

    public static class XSServiceAdvice {
        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.This Object dispather,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2ServiceActionInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            callDepth = CallDepth.forClass(XSStruts2ServiceActionCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            Context parentContext = currentContext();
            if (!instrumenter().shouldStart(parentContext, dispather)) {
                return;
            }
            parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
            context = instrumenter().start(parentContext, dispather);
            context = BaggageUtil.syncBaggage().build().storeInContext(context);
            scope = context.makeCurrent();
            durationPrinter.printElapseDuration("XSServiceAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.Thrown Throwable throwable,
                @Advice.Argument(0) HttpServletRequest request,
                @Advice.Argument(1) HttpServletResponse response,
                @Advice.Argument(2) Object actionMapping,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2ServiceActionInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope != null) {
                scope.close();
                UserRequest ur = UserRequest.builder().build();
                ur.setRequest(request);
                // ur.setResponse(response);
                ur.setAnyObject(actionMapping);
                instrumenter().end(context, null , ur, throwable);
            }
            durationPrinter.printElapseDuration("XSServiceAdvice e");
        }
    }
}
